<template>
    <div class="img-verify">
        <canvas ref="verify" width="120" height="40" @click="updateImgCode"></canvas>
    </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, Ref, ref } from "vue";
import { useVerifyStore } from '../store/verify'
const verifyStore = useVerifyStore()

const verify: Ref = ref(null)
const state = reactive({
    pool: 'QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm0123456789',
    imgCode: ''
})
const updateImgCode = () => {
    verifyStore.setRegisterImgCode(draw())
}

onMounted(() => {
    verifyStore.setRegisterImgCode(draw())
})
//生成随机数
const randomNum = (min: number, max: number): number => {
    return Math.floor(Math.random() * (max - min) + min)
}
//生成随机颜色
const randomColor = (min: number, max: number): string => {
    const r = randomNum(min, max)
    const g = randomNum(min, max)
    const b = randomNum(min, max)
    return `rgb(${r},${g},${b})`
}
//画验证码
const draw = (): string => {
    const ctx = verify.value.getContext('2d');
    ctx.fillStyle = randomColor(180, 230)
    ctx.fillRect(0, 0, 120, 40)
    let imgCode = ''
    // 生成随机四个字符
    for (let i = 0; i < 4; i++) {
        const text = state.pool[randomNum(0, state.pool.length)]
        imgCode += text
        const fontSize = randomNum(28, 40)
        const deg = randomNum(-30, 30)
        ctx.font = fontSize + 'px Simhei'
        ctx.textBaseline = 'top'
        ctx.fillStyle = randomColor(80, 150)
        ctx.save()
        ctx.translate(30 * i + 15, 15)
        ctx.rotate(deg * Math.PI / 180)
        ctx.fillText(text, -10, -15)
        ctx.restore()
    }
    // 5.随机产生5条干扰线,干扰线的颜色要浅一点
    for (let i = 0; i < 5; i++) {
        ctx.beginPath()
        ctx.moveTo(randomNum(0, 120), randomNum(0, 40))
        ctx.lineTo(randomNum(0, 120), randomNum(0, 40))
        ctx.strokeStyle = randomColor(180, 230)
        ctx.closePath()
        ctx.stroke()
    }
    // 6.随机产生40个干扰的小点
    for (let i = 0; i < 40; i++) {
        ctx.beginPath()
        ctx.arc(randomNum(0, 120), randomNum(0, 40), 1, 0, 2 * Math.PI)
        ctx.closePath()
        ctx.fillStyle = randomColor(150, 200)
        ctx.fill()
    }
    return imgCode
}
</script>